<template>
    <div class="app-container">
  
      <!-- 查询和其他操作 -->
       <el-form :inline="true" class="demo-form-inline filter">
         <div>
        <el-form-item label="退货日期">
           <el-date-picker
            v-model="alarmdate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
          </el-form-item>
  
          <el-form-item label="单据编号"><el-input
          v-model="listQuery.fbillno"
          clearable
          class="filter-item"
          placeholder="请输入单据编号"
        /></el-form-item>
         <el-form-item label="单据状态">
            <el-select
          v-model="listQuery.fbillstate"
          class="filter-item"
          clearable
          placeholder="请选择单据状态"
        >
          <el-option
            v-for="item in fbillstateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
          </el-form-item>
          <el-form-item label="仓库名称">
            <el-select
            v-model="listQuery.fstockno"
            class="filter-item"
            clearable
            placeholder="请选择仓库名称"
          >
            <el-option
              v-for="item in fstocknoOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          </el-form-item>
          </div>
          <div>
                  <el-form-item class="searchOne" label="退货人员">
        <div style="display:flex;justify-content:flex-start;align-items:center">
                  <el-select style="display: inline-block" clearable filterable v-model="listQuery.fretuser" class="filter-item" placeholder="请选择退货人员">
                  <el-option
                  v-for="item in getListfretuser"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
                </el-select>
                  <i class="el-icon-search selectI" @click="searchDialoguse('search')"/>
                </div>
        </el-form-item>
        <el-form-item label="供应商">
          <div style="display:flex;justify-content:flex-start;align-items:center">
                  <el-select style="display: inline-block" v-model="listQuery.fsupno" filterable clearable class="filter-item" placeholder="请选择供应商">
                <el-option
                  v-for="item in getListfsupno"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
                  <i class="el-icon-search selectI" @click="searchDialogsupno('search')"/>
                </div>
        </el-form-item>
        <el-form-item>
        <el-button round size="medium" class="filter-item" :style="{background:buttonColor.lookup,color:buttonColor.color}" @click="handleFilter">查找</el-button>
        <el-button round size="medium" class="filter-item" :style="{background:buttonColor.add,color:buttonColor.color}" @click="handleCreate">添加</el-button>
        <el-button round size="medium" :style="{background:buttonColor.import,color:buttonColor.color}" @click="handleUpload">导入</el-button>
        </el-form-item>
        </div>
        </el-form>
  
      <!-- 查询结果 -->
      <el-table :height="buttonColor.clientHeightTwo" v-loading="listLoading" :data="list" stripe element-loading-text="正在查询中。。。" border fit highlight-current-row :header-cell-style="tableColor">
           <el-table-column :width="buttonColor.operationThree" align="center" label="操作" class-name="small-padding">
          <template slot-scope="scope">
          <div class="operationButton">
              <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" />
              编辑
            </div>
            <div v-if="scope.row.fbillstate === 1" :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete(scope.row)">
              <img src="../../../public/images/del.png" />
              删除
            </div>
            <div v-else :style="{color:buttonColor.delete,cursor:'pointer'}">
              <img src="../../../public/images/del.png" />
              删除
            </div>
              <div v-if="scope.row.fbillstate === 1" :style="{color:buttonColor.examine,cursor:'pointer'}" @click="audit(scope.row)">
              <img src="../../../public/images/examine.png" />
              确认
            </div>
             <div v-else :style="{color:buttonColor.examine,cursor:'pointer'}">
              <img src="../../../public/images/examine.png" />
              确认
            </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序号" type="index" />
        <el-table-column :width="buttonColor.billno" align="left" label="单据编号" prop="fbillno" />
        <el-table-column :formatter="formatfstockno" align="left" label="仓库名称" prop="fstockno" />
        <el-table-column :width="buttonColor.user" :formatter="formatfretuser" align="left" label="退货人员" prop="fretuser"/>
        <el-table-column :width="buttonColor.date" :formatter="datetimeFormat" align="left" label="退货日期" prop="fretdate"/>
        <el-table-column :width="buttonColor.user" :formatter="formatfsupno" align="left" label="供应商" prop="fsupno" />
        <el-table-column :width="buttonColor.num" align="center" label="品项数" prop="fitemcount" />
        <el-table-column :width="buttonColor.num" align="center" label="总件数" prop="fpiececount" />
        <el-table-column :width="buttonColor.num" align="center" label="总价" prop="ftotalamt" />
         <el-table-column :width="buttonColor.state" align="left" label="单据状态" prop="fbillstate" >
            <template slot-scope="scope">
            <span
              :style="{color:buttonColor.itemisconfirmed}"
              v-if="scope.row.fbillstate === 1"
              >{{ scope.row.fbillstate | statusFilter }}</span
            >
            <span :style="{color:buttonColor.itemconfirmed}" v-else-if="scope.row.fbillstate === 2">{{
              scope.row.fbillstate | statusFilter
            }}</span>
            <span :style="{color:buttonColor.iteminvalid}" v-else>{{
              scope.row.fbillstate | statusFilter
            }}</span>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  
      <!-- 添加或修改对话框 -->
      <el-dialog width="98%" :close-on-click-modal="false" :before-close="handleClose" :visible.sync="dialogFormVisible">
        <template slot="title">
        <div :style="titleColor">{{textMap[dialogStatus]}}</div>
      </template>
        <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="80px">
         <el-row>
            <el-col :span="6">
              <el-form-item class="required" label="单据编号" prop="fbillno">
            <el-input disabled v-model="dataForm.fbillno"/>
          </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item class="required" label="退货日期" prop="fretdate">
            <el-date-picker disabled v-model="dataForm.fretdate" type="date" style="width:200px"/>
          </el-form-item>
            </el-col>
           <el-col :span="6">
             <el-form-item class="required" label="单据状态" prop="fbillstate">
            <el-select
                  disabled
                  v-model="dataForm.fbillstate"
                  class="filter-item"
                  clearable
                >
                  <el-option
                    v-for="item in fbillstateOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
          </el-form-item>
           </el-col>
                 <el-col :span="6">
              <el-form-item class="required" label="供应商" prop="fsupno">
            <div style="display:flex;justify-content:flex-start;align-items:center">
                  <el-select style="display: inline-block" v-model="dataForm.fsupno" filterable clearable class="filter-item" placeholder="请选择供应商">
                <el-option
                  v-for="item in getListfsupno"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
                  <i class="el-icon-search selectI" @click="searchDialogsupno('add')"/>
                </div>
          </el-form-item>
           </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item class="required" label="仓库名称" prop="fstockno">
            <el-select
            v-model="dataForm.fstockno"
            class="filter-item"
            clearable
          >
            <el-option
              v-for="item in fstocknoOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          </el-form-item>
            </el-col>
            <el-col :span="6">
          <el-form-item class="required" label="退货人员" prop="fretuser">
             <div style="display:flex;justify-content:flex-start;align-items:center">
                  <el-select style="display: inline-block" clearable filterable v-model="dataForm.fretuser" class="filter-item" placeholder="请选择采购人员">
                  <el-option
                  v-for="item in getListfretuser"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
                </el-select>
                  <i class="el-icon-search selectI" @click="searchDialoguse('add')"/>
                </div>
          </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="text" style="width:94%" label="备注" prop="fexplanation">
            <el-input v-model="dataForm.fexplanation"/>
          </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <div :style="{width:'100%',display:'flex',border: '2px solid #F2F2F2',height:panelHeight}">
          <div v-if="!viewFlag" style="width:343px" class="tableLeft">
               <el-form ref="dataForm1" :rules="rules1" :model="dataForm1" status-icon label-position="left" label-width="auto">
                <el-form-item class="required" label="行号" prop="fline">
                  <el-input v-model.number="dataForm1.fline" disabled/>
                </el-form-item>
                <el-form-item class="required" label="耗材编号" prop="fmaterialno">
                  <div v-if="!viewFlag" style="display:flex;justify-content:flex-start;align-items:center">
                        <el-input v-model="dataForm1.fmaterialno" style="display: inline-block" />
                        <i class="el-icon-search selectI" @click="searchDialogMaterial()"/>
                      </div>
                      <div v-else style="display:flex;justify-content:flex-start;align-items:center">
                        <el-input disabled v-model="dataForm1.fmaterialno" style="display: inline-block" />
                      </div>
                </el-form-item>
                <el-form-item label="耗材名称" prop="fmaterialname">
                  <el-input disabled v-model="dataForm1.fmaterialname"/>
                </el-form-item>
                <el-form-item label="采购价" prop="fbuypriceData">
                  <el-input disabled v-model="fbuypriceData" />
                </el-form-item>
                <el-form-item label="采购单位" prop="fordunit">
                  <el-input  v-model.number="dataForm1.fordunit" disabled/>
                </el-form-item>
                <el-form-item label="数量" prop="fqtyData">
                  <el-input v-model.number="fqtyData" maxlength="6"/>
                </el-form-item>
                <el-form-item label="合计" prop="ftotamtData">
                  <el-input :disabled="true" v-model.number="ftotamtData" />
                </el-form-item>
                <el-form-item label="生产日期" prop="fprocdate">
                  <el-date-picker disabled v-model="dataForm1.fprocdate" type="date"/>
                </el-form-item>
                <el-form-item label="备注" prop="fmemo">
                  <el-input v-model="dataForm1.fmemo"/>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button round size="medium" :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="cancle1">取消</el-button>
                <el-button round :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="editData1">确定</el-button>
              </div>
          </div>
          <el-tabs :class="!viewFlag? 'tableWidth' : 'tableWidthAll'" type="border-card">
          <el-tab-pane label="耗材列表">
             <div class="filter-container">
                <!-- 查询结果 -->
                <el-table :height="panelHeight" v-loading="listLoading" :data="dataForm.details" stripe element-loading-text="正在查询中。。。" border fit highlight-current-row :header-cell-style="tableColor">
                  <el-table-column :width="buttonColor.line" align="center" label="行号" prop="fline" />
                  <el-table-column align="left" label="耗材编号" prop="fmaterialno" />
                  <el-table-column :formatter="good" align="left" label="耗材名称" prop="fmaterialname" />
                  <el-table-column align="center" label="采购价" prop="fbuyprice" />
                  <el-table-column align="center" label="数量" prop="fqty" />
                  <el-table-column align="center" label="合计" prop="ftotamt" />
                  <el-table-column :formatter="datetimeFormat" align="left" label="生产日期" prop="fprocdate" />
                  <el-table-column align="left" label="备注" prop="fmemo" />
                  <el-table-column :width="buttonColor.operationTwo" v-if="isshow" align="center" label="操作" class-name="small-padding">
                    <template slot-scope="scope">
                    <div class="operationButton">
                        <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleEdit1(scope.row)">
                        <img src="../../../public/images/edit.png" />
                        编辑
                      </div>
                      <div :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete1(scope.row)">
                        <img src="../../../public/images/del.png" />
                        删除
                      </div>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
          </el-tab-pane></el-tabs>
        </div>
        <div slot="footer" class="dialog-footer">
          <div v-if="viewFlag==false">
            <el-button round :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="cancel()">取消</el-button>
           <el-button round v-if="dialogStatus=='create'" :style="{background:buttonColor.confirm,color:buttonColor.color}"  @click="createData">确定</el-button>
           <el-button round v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
          </div>
          <div v-else>
            <el-button round :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="cancel()">取消</el-button>
            <el-button round v-if="dialogStatus=='create'" :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="createData">确定</el-button>
          </div>
        </div>
      </el-dialog>
  
       <!-- 导出弹窗 -->
      <el-dialog width="auto" :close-on-click-modal="false" :visible.sync="uploadVisible">
        <template slot="title">
        <div :style="exportColor">采购出库</div>
      </template>
        <div style="width:300px;height:200px;display: flex;flex-direction: column;align-items: center">
             <el-upload
            :on-success="uploadFileSuccess"
            :headers="headers"
            :action="uploadPath2"
            :data="{'tableName':'Import_m_tc_ret_detail'}"
            :show-file-list="false"
            class="filter-item"
            style="margin-top:20px"
            accept=".xlsx">
            <el-button round size="medium" icon="el-icon-upload" :style="{background:buttonColor.import,color:buttonColor.color}">导入</el-button>
          </el-upload>
          <div style="margin-top:30px;text-decoration:underline">
            <a :href="downUrl" style="color: blue">模板文件下载</a>
          </div>
  
        </div>
      </el-dialog>
  
      <Consumables
        :materialIdVisible.sync="materialIdVisible"
        :fsiteNo.sync="materialFsiteNo" 
        :tableColor="tableColor" 
        @materialDialog="materialDialogValue"
       ref="Consumables"/>
      <userDialog :searchVisibleuse.sync="searchVisibleuse" :fsiteNo.sync="userDialogFsiteNo" :tableColor="tableColor" @userDialog="userDialogValue" />
      <!-- <material :materialIdVisible.sync="materialIdVisible" :fsiteNo.sync="materialFsiteNo" :tableColor="tableColor" @materialDialog="materialDialogValue" /> -->
      <supnoDialog :supnoVisible.sync="supnoVisible" :tableColor="tableColor" @supnoDialog="supnoDialogValue" />
    </div>
  </template>
  
  <style>
    .button-margin {
      margin : 2px 0px;
    }
    .el-button+.el-button {
      margin-left: 1px;
    }
  
  </style>
  
  <script>
  import { listretHead, createretHead, updateretHead, deleteretHead } from '@/api/haocai/retHead'
  import { listgoodInfo } from "@/api/goodInfo"
  import Pagination from '@/components/Pagination'
  import UserDialog from '@/components/UserDialog'
  import Consumables from "@/components/Consumables"
  import Material from '@/components/Material'
  import {listgoodInfolist} from '@/api/haocai/goodInfo'
  import SupnoDialog from '@/components/SupnoDialog'
  import moment from 'moment'
  import { tableColor,titleColor,exportColor,buttonColor } from '@/filters/index'
  import { getListArea, getFbillno, checkBiz, uploadPath2 } from "@/api/area";
  import { getToken } from '@/utils/auth';
  import { getApiUrl } from '@/utils/request'
  
  const statusMap = {
    1: '待出库',
    2: '已出库',
    8: '已作废'
  }
  
  export default {
    name: 'ITcRetHead',
    components: { Pagination, UserDialog, Material, SupnoDialog,Consumables },
    filters: {
      statusFilter(type) {
        return statusMap[type]
      }
    },
    data() {
      return {
        isAdd1: true,
        panelHeight: 0,
        downUrl: null,
        uploadVisible: false,
        uploadPath2,
        buttonColor,
        isshow:true,
        isActive:false,
        viewFlag:false,
        supnoFlag: false,
        supnoVisible: false,
        userFlag:null,
        haocailist:[],
        searchVisibleuse: false,
        userDialogFsiteNo:null,
        materialIdVisible: false,
        materialFsiteNo: null,
  
        goodAllList: [],
        goodInfoList: [],
        getListfretuser:[],
        dialogFormVisible1: false,
        detailsTmp: [],
        listTmp: [],
         dataForm1: {
          fline: undefined,
          fmaterialno: undefined,
          fmaterialname: undefined,
          fbuyprice: undefined,
          fspec: undefined,
          funit: undefined,
          fordunit:undefined,
          fqty: undefined,
          ftotamt: undefined,
          fmemo: undefined,
          fprocdate: undefined,
        },
        flineList:[],
        selectList:[],
        fbuypriceData: 0,
        fqtyData: 1,
        ftotamtData: 0,
        fstocknoOptions: [],
  
        getListfsupno: [],
        list: null,
        total: 0,
        listLoading: true,
        alarmdate: null,
        listQuery: {
          page: 1,
          limit: 20,
          fstockno: undefined,
          fsiteNo: this.$store.state.user.fsiteNo,
          fretuser: undefined,
          fretdate: undefined,
          ftakedateStart: undefined,
          ftakedateEnd: undefined,
          fsupno: undefined,
          fitemcount: undefined,
          fpiececount: undefined,
          ftotalamt: undefined,
          fbillno: undefined,
          fexplanation: undefined,
          fupddate: undefined,
          foperator: undefined,
          fcheckdate: undefined,
          fcheckuser: undefined,
          fbillstate: undefined,
          sort: 'create_time',
          order: 'desc'
        },

        dataForm: {
          fstockno: undefined,
          fsiteNo: undefined,
          fretuser: undefined,
          fretdate: undefined,
          fsupno: undefined,
          fitemcount: undefined,
          fpiececount: undefined,
          ftotalamt: undefined,
          fbillno: undefined,
          fexplanation: undefined,
          fupddate: undefined,
          foperator: undefined,
          fcheckdate: undefined,
          fcheckuser: undefined,
          fbillstate: undefined,
          id: undefined,
          details: []
        },
        tableColor,
        titleColor,
        exportColor,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          fstockno: [
            { required: true, message: '仓库名称不能为空' },
          ],
          fsiteNo: [
            { required: true, message: '客户名称不能为空' },
          ],
          fretuser: [
            { required: true, message: '退货人员不能为空' },
          ],
          fretdate: [
            { required: true, message: '退货日期不能为空' },
          ],
          fsupno: [
            { required: true, message: '供应商不能为空' },
          ],
          fitemcount: [
            { type: 'number', message: '品项数必须为数字值' },
          ],
          fpiececount: [
            { type: 'number', message: '总件数必须为数字值' },
          ],
          fbillstate: [
            { type: 'number', message: '单据状态必须为数字值' },
          ],
        },
        rules1: {
          fline: [
            { required: true, message: '行号不能为空' },
            { type: 'number', message: '行号必须为数字值' },
          ],
          fmaterialno: [
            { required: true, message: '耗材编号不能为空' },
          ],
          fbuyprice: [
            { required: true, message: '采购价不能为空' },
          ],
          fqty: [
            { required: true, message: '数量不能为空' },
          ],
          ftotamt: [
            { required: true, message: '合计不能为空' },
          ],
        },
         fbillstateOptions: [
          { value: 1, label: '待出库' },
          { value: 2, label: '已出库' },
          { value: 8, label: '已作废' },
        ]
      }
    },
    created() {
      this.downUrl = getApiUrl() + 'xlsx/7-3出库明细.xlsx'
      this.panelHeight = document.documentElement.clientHeight-294
      this.alarmdate = [this.parserDate(moment(new Date().setDate(1)).format('YYYY-MM-DD')), new Date()]
      this.getList()
      // 人员弹出框
        getListArea({flag:13,arg1:this.$store.state.user.fsiteNo})
        .then(response => {
          this.getListfretuser = response.data.data.list
        })
        .catch(() => {
          this.getListfretuser = []
        })
        // 供应商
      getListArea({ flag: 6,arg1:this.$store.state.user.fsiteNo })
        .then(response => {
          this.getListfsupno = response.data.data.list
        })
        .catch(() => {
          this.getListfsupno = []
        })
  
         // 仓库名称
      getListArea({ flag: 30,arg1:this.$store.state.user.fsiteNo })
        .then(response => {
          this.fstocknoOptions = response.data.data.list
        })
        .catch(() => {
          this.fstocknoOptions = []
        })
  
        // 耗材
      getListArea({ flag: 31 })
        .then(response => {
          this.goodAllList = response.data.data.list
        })
        .catch(() => {
          this.goodAllList = []
        })
        // 耗材信息
        listgoodInfo({ limit: -1,fsiteNo:this.$store.state.user.fsiteNo })
        .then(response => {
          this.goodInfoList = response.data.data.list
        })
        .catch(() => {
          this.goodInfoList = []
        })
        //耗材资料
        listgoodInfolist({limit: 20,fsiteNo:this.$store.state.user.fsiteNo})
        .then((res)=>{
          this.haocailist=res.data.data.list
        })
    },
    watch: {
      fbuypriceData: function(val) {
        if(this.fqtyData&&val){
          const num = (this.fqtyData * parseFloat(val)).toFixed(2)
        return this.ftotamtData=num
        }else{
          return this.ftotamtData=0
        }
      },
  
      fqtyData: function(val) {
         if(this.fqtyData&&val){
           const num = (parseFloat(this.fbuypriceData)  * val).toFixed(2)
        return this.ftotamtData=num
        }else{
          return this.ftotamtData=0
        }
  
      }
  
    },
      computed: {
      headers() {
        return {
          'Authorization': getToken()
        }
      }
    },
    methods: {
      uploadFileSuccess: function(response) {
        this.uploadVisible = false
        this.$notify.success({
          title: '导入',
          dangerouslyUseHTMLString:true,
          message: response.data
        })
      },
      handleUpload(){
        this.uploadVisible = true
      },
      parserDate(date) {
        var t = Date.parse(date)
        if (!isNaN(t)) {
          return new Date(Date.parse(date.replace(/-/g, '/')))
        }
      },
      datetimeFormat(row, column) {
        const date = row[column.property]
        if (date === undefined || date === null) {
          return ''
        }
        return moment(date).format('YYYY-MM-DD')
      },
      formatDate: function(date) {
        if(typeof(date)==='object'){
           var ym
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        var d = date.getDate()
        if (m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        ym = '' + y + m + d
        return ym
        }else{
          return date
        }
  
      },
       // 耗材
      formatfgoodno: function(row, column) {
        if (this.goodAllList.length > 0) {
          for (let i = 0; i < this.goodAllList.length; i++) {
            if (row.fmaterialno === this.goodAllList[i].value) {
              return this.goodAllList[i].label
            }
          }
          return ''
        } else {
          return ''
        }
      },
      // 耗材
      good: function(row, column) {
        if (this.haocailist.length > 0) {
          for (let i = 0; i < this.haocailist.length; i++) {
            console.log(row.fmaterialno,this.haocailist[i].fmaterialno)
            if (row.fmaterialno === this.haocailist[i].fmaterialno) {
              return this.haocailist[i].fmaterialname
            }
          }
          return ''
        } else {
          return ''
        }
      },
      // 采购单位
      formatfordunit: function(row, column) {
        if (this.goodInfoList.length > 0) {
          for (let i = 0; i < this.goodInfoList.length; i++) {
            if (row.fmaterialno === this.goodInfoList[i].fmaterialno) {
              return this.goodInfoList[i].fordunit
            }
          }
          return ''
        } else {
          return ''
        }
      },
      // 仓库名称
      formatfstockno: function(row, column) {
        if (this.fstocknoOptions.length > 0) {
          for (let i = 0; i < this.fstocknoOptions.length; i++) {
            if (row.fstockno === this.fstocknoOptions[i].value) {
              return this.fstocknoOptions[i].label
            }
          }
          return ''
        } else {
          return ''
        }
      },
      // 供应商
      formatfsupno: function(row, column) {
        if (this.getListfsupno.length > 0) {
          for (let i = 0; i < this.getListfsupno.length; i++) {
            if (row.fsupno === this.getListfsupno[i].value) {
              return this.getListfsupno[i].label
            }
          }
          return ''
        } else {
          return ''
        }
      },
      // 供应商弹出框
      searchDialogsupno(value) {
        this.supnoFlag = value
        this.supnoVisible = true
      },
  
      // 供应商弹出框
      supnoDialogValue(value){
        if(this.supnoFlag==='add'){
          this.dataForm.fsupno = value.data.fsupno
        }else{
          this.listQuery.fsupno = value.data.fsupno
        }
      },
       // 耗材弹出框
      searchDialogMaterial() {
        this.materialIdVisible = true
        this.materialFsiteNo = this.dataForm.fsiteNo
      },
  
      // 耗材弹出框
      materialDialogValue(value){
          this.dataForm1.fmaterialno = value.data.fmaterialno
          this.dataForm1.fmaterialname = value.data.fmaterialname
          //this.dataForm1.fbuyprice = value.data.fbuyprice
          //this.dataForm1.fordunit = value.data.fordunit
          this.fbuypriceData = value.data.fbuyprice
          this.dataForm1.fspec = value.data.fspec
          this.dataForm1.funit = value.data.funit
      },
      // 搜索人员弹出框
      searchDialoguse(value) {
        this.userFlag = value
        if(value === 'add'){
          this.userDialogFsiteNo = this.dataForm.fsiteNo
        }else{
          this.userDialogFsiteNo = this.listQuery.fsiteNo
        }
        this.searchVisibleuse = true
      },
  
      // 人员弹出框返回值
      userDialogValue(value){
        if(this.userFlag==='add'){
          this.dataForm.fretuser = value.user.id.toString()
        }else{
          this.listQuery.fretuser = value.user.id.toString()
        }
      },
  
      // 人员回显
      formatfretuser: function(row, column) {
        if(this.getListfretuser){
          for (let i = 0; i < this.getListfretuser.length; i++) {
          if (row.fretuser == this.getListfretuser[i].value) {
            return this.getListfretuser[i].label
          }
        }
        return ''
        }else{
        return ''
        }
      },
      getList() {
        this.listQuery.ftakedateStart = this.alarmdate == null ? null : this.formatDate(this.alarmdate[0])
        this.listQuery.ftakedateEnd = this.alarmdate == null ? null : this.formatDate(this.alarmdate[1])
        this.listLoading = true
        listretHead(this.listQuery)
          .then(response => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          fstockno: undefined,
          fsiteNo: undefined,
          fretuser: undefined,
          fretdate: undefined,
          fsupno: undefined,
          fitemcount: undefined,
          fpiececount: undefined,
          ftotalamt: undefined,
          fbillno: undefined,
          fexplanation: undefined,
          fupddate: undefined,
          foperator: undefined,
          fcheckdate: undefined,
          fcheckuser: undefined,
          fbillstate: undefined,
          id: undefined,
          details: []
        }
      },
      resetForm1(){
         this.dataForm1={
          fline: undefined,
          fmaterialno: undefined,
          fmaterialname: undefined,
          fbuyprice: undefined,
          fspec: undefined,
          funit: undefined,
          fordunit:undefined,
          fqty: undefined,
          ftotamt: undefined,
          fmemo: undefined,
          fprocdate: undefined,
        }
      },
      handleCreate() {
        this.resetForm()
        this.viewFlag = false
        // 单据编号
        getFbillno({ flag: 2019 })
          .then((response) => {
            if (response) {
              this.dataForm.fbillno = response.data.data
              this.dialogFormVisible = true
              this.$nextTick(() => {
              this.$refs['dataForm'].clearValidate()
            })
            }
          })
          .catch(() => {
            this.dataForm.fbillno = ''
          })
          if (this.getListfsupno.length > 0) {
          this.dataForm.fsupno = this.getListfsupno[0].value
        }
        if (this.fstocknoOptions.length > 0) {
          this.dataForm.fstockno = this.fstocknoOptions[0].value
        }
        this.dataForm.fbillstate=1
        this.dataForm.fretdate=new Date()
        this.dataForm.fsiteNo = this.$store.state.user.fsiteNo;
        this.dataForm.fretuser=this.$store.state.user.id.toString()
        this.dialogStatus = 'create'
        // 子表1
        this.handleUpdate1()
        this.resetForm1();
        this.dataForm1.fline = 1
        this.fbuypriceData = 0
        this.fqtyData = 1
        this.ftotamtData = 0
        this.dataForm1.fprocdate=new Date()
      },
      createData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            createretHead(this.dataForm)
              .then(response => {
                this.list.unshift(response.data.data)
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加耗材出库主表成功'
                })
                this.selectList=[]
                this.flineList=[]
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.data
                })
              })
          }
        })
      },
      handleUpdate(row) {
        if(row.fbillstate == 2)
        {
          this.isshow = false;
          this.viewFlag = true
        }
        else
        {
           this.isshow = true
           this.viewFlag = false
        }
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
          this.detailsTmp = [];
        this.listTmp = row;
        row.details.forEach((v) => {
          this.detailsTmp.push(v);
          this.selectList.push(v.fmaterialno)
          this.flineList.push(v.fline)
        });
        if(row.fbillstate == 2)
        {
          this.isActive = true
        }
        else
        {
           this.isActive = false
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
  
          // 子表1
        this.handleUpdate1()
        this.resetForm1();
        this.fbuypriceData = 0
        this.fqtyData = 1
        this.ftotamtData = 0
        this.dataForm1.fprocdate=new Date()
        if(this.dataForm.details.length > 0){
           // 计算行号
          let len = this.dataForm.details.length - 1
          this.dataForm1.fline = this.dataForm.details[len].fline + 1
        }else{
          this.dataForm1.fline = 1
        }
      },
      audit(row) {
        this.$confirm('是否确定', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dataForm = Object.assign({}, row)
          checkBiz({ pBillNo: this.dataForm.fbillno ,pBillState:2 ,pBizType: 'm_tc_ret_head', pUser:this.$store.state.user.id })
              .then(() => {
                for (const v of this.list) {
                  if (v.fbillno === this.dataForm.fbillno) {
                    this.dataForm.fbillstate = 2
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.$notify.success({
                  title: '成功',
                  message: '确认成功'
                })
              })
              .catch((response) => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.data
                })
              })
        }).catch(()=>{})
      },
      updateData() {
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            updateretHead(this.dataForm, this.$route.query.id)
              .then(() => {
                for (const v of this.list) {
                  if (v.fbillno === this.dataForm.fbillno) {
                    const index = this.list.indexOf(v)
                    this.list.splice(index, 1, this.dataForm)
                    break
                  }
                }
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新耗材出库主表成功'
                })
                this.selectList=[]
                this.flineList=[]
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.data
                })
              })
          }
        })
      },
      handleDelete(row) {
        this.$confirm('是否要删除耗材出库主表', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteretHead(row)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除耗材出库主表成功'
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }).catch(()=>{})
      },
  
      cancel() {
        this.isshow = true
        this.dialogFormVisible = false
        this.selectList=[]
        this.flineList=[]
        this.list.forEach((v) => {
          if (v.fbillno === this.dataForm.fbillno) {
            this.dataForm = this.listTmp
            this.dataForm.details = this.detailsTmp
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, this.dataForm)
            return
          }
        })
      },
  
      // 弹窗点击关闭前的回调
        handleClose(){
          this.isshow = true
          this.dialogFormVisible = false
          this.selectList=[]
          this.flineList=[]
          this.list.forEach((v) => {
            if (v.fbillno === this.dataForm.fbillno) {
              this.dataForm = this.listTmp
              this.dataForm.details = this.detailsTmp
              const index = this.list.indexOf(v)
              this.list.splice(index, 1, this.dataForm)
              return
            }
          })
        },
  
       handleUpdate1() {
        this.$nextTick(() => {
          this.$refs["dataForm1"].clearValidate();
        });
      },
  
  
       // 子表一添加编辑
      handleEdit1(row){
            this.dataForm1 = Object.assign({}, row);
              this.fbuypriceData = row.fbuyprice
              this.fqtyData = row.fqty
              this.ftotamtData = row.ftotamt
              this.dataForm1.fordunit = this.formatfordunit(row)
              this.dataForm1.fmaterialname = this.formatfgoodno(row)
            // 清除验证
            this.$nextTick(() => {
              this.$refs["dataForm1"].clearValidate();
            });
  
      },
      // 子表一编辑保存数据
      editData1() {
        this.$refs["dataForm1"].validate((valid) => {
          if (valid) {
            if(this.dataForm.details.length > 0){
              let temp = [...this.dataForm.details]
              let isRepeat= false
              // 子表编辑
               for (const v of this.dataForm.details) {
                if (v.fline === this.dataForm1.fline) {
                  const index = this.dataForm.details.indexOf(v);
                  this.dataForm1.fbuyprice = this.fbuypriceData
                  this.dataForm1.fqty = this.fqtyData
                  this.dataForm1.ftotamt = this.ftotamtData
                  // 判断耗材是否重复
                  temp.splice(index, 1);
                   for (const vi of temp) {
                     if(vi.fmaterialno == this.dataForm1.fmaterialno){
                       isRepeat = true
                        this.$notify.error({
                              title: '失败',
                              message: '所选耗材重复'
                            })
                        return;
                     }
                   }
  
                   if(!isRepeat){
                        this.dataForm.details.splice(index, 1, this.dataForm1);
                        this.selectList.splice(index, 1, this.dataForm1.fmaterialno);
                      this.isAdd1 = false
                      break;
                   }
  
                }
              }
              // 子表添加
              if(this.isAdd1){
                   this.dataForm1.fbuyprice = parseFloat(this.fbuypriceData)
                      this.dataForm1.fqty = this.fqtyData
                      this.dataForm1.ftotamt =parseFloat(this.ftotamtData)
                      // 判断行号是否重复
                    const flinetem = this.flineList.indexOf(this.dataForm1.fline)
                    // 判断耗材id是否重复
                    const tem = this.selectList.indexOf(this.dataForm1.fmaterialno)
                    if(flinetem<0){
                        if(tem<0){
                        if (valid) {
                        this.dataForm.details.push(this.dataForm1)
                        this.selectList.push(this.dataForm1.v)
                        this.flineList.push(this.dataForm1.fline)
                        }
                      }else{
                        this.$notify.error({
                              title: '失败',
                              message: '所选耗材重复'
                            })
                        return;
                      }
                    }else{
                      this.$notify.error({
                            title: '失败',
                            message: '行号重复'
                          })
                      return;
                    }
              }
            }else{
                    // 子表第一次添加
                      this.dataForm1.fbuyprice = parseFloat(this.fbuypriceData)
                      this.dataForm1.fqty = this.fqtyData
                      this.dataForm1.ftotamt =parseFloat(this.ftotamtData)
                      // 判断行号是否重复
                    const flinetem = this.flineList.indexOf(this.dataForm1.fline)
                    // 判断耗材id是否重复
                    const tem = this.selectList.indexOf(this.dataForm1.fmaterialno)
                    if(flinetem<0){
                        if(tem<0){
                        if (valid) {
                        this.dataForm.details.push(this.dataForm1)
                        this.selectList.push(this.dataForm1.fmaterialno)
                        this.flineList.push(this.dataForm1.fline)
                        }
                      }else{
                        this.$notify.error({
                              title: '失败',
                              message: '所选耗材重复'
                            })
                        return;
                      }
                    }else{
                      this.$notify.error({
                            title: '失败',
                            message: '行号重复'
                          })
                      return;
                    }
            }
              this.resetForm1()
              this.isAdd1 = true
              // 清除验证
              this.$nextTick(() => {
                this.$refs["dataForm1"].clearValidate();
              });
              // 计算行号
              if(this.dataForm.details.length > 0){
                // 计算行号
                let len = this.dataForm.details.length - 1
                this.dataForm1.fline = this.dataForm.details[len].fline + 1
              }else{
                this.dataForm1.fline = 1
              }
              this.fbuypriceData = 0
              this.fqtyData = 1
              this.ftotamtData = 0
              this.dataForm1.fprocdate=new Date()
          }
        });
      },
  
      cancle1(){
           this.resetForm1()
           this.isAdd1 = true
  
            // 清除验证
            this.$nextTick(() => {
              this.$refs["dataForm1"].clearValidate();
            });
  
          // 计算行号
          if(this.dataForm.details.length > 0){
            // 计算行号
            let len = this.dataForm.details.length - 1
            this.dataForm1.fline = this.dataForm.details[len].fline + 1
          }else{
            this.dataForm1.fline = 1
          }
          this.fbuypriceData = 0
          this.fqtyData = 1
          this.ftotamtData = 0
          this.dataForm1.fprocdate=new Date()
      },
  
       handleDelete1(row) {
          this.$confirm('是否要删除耗材', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            const index = this.dataForm.details.indexOf(row);
            this.dataForm.details.splice(index, 1);
            this.selectList.splice(index,1)
            this.flineList.splice(index,1)
  
            this.resetForm1()
            if(this.dataForm.details.length > 0){
              // 计算行号
              let len = this.dataForm.details.length - 1
              this.dataForm1.fline = this.dataForm.details[len].fline + 1
            }else{
              this.dataForm1.fline = 1
            }
            this.fbuypriceData = 0
            this.fqtyData = 1
            this.ftotamtData = 0
            this.dataForm1.fprocdate=new Date()
        }).catch(()=>{})
      },
  
      indexMethod(index) {
        index = index + 1
        return index
      }
    }
  }
  </script>
  